package com.hit.aircraftwar.httputil;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.hit.aircraftwar.activity.MainActivity;
import com.hit.aircraftwar.activity.RoomActivity;
import com.hit.aircraftwar.setter.ParameterSet;
import com.rabtman.wsmanager.WsManager;
import com.rabtman.wsmanager.listener.WsStatusListener;
import com.zhy.http.okhttp.cookie.CookieJarImpl;
import com.zhy.http.okhttp.cookie.store.PersistentCookieStore;

import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import okhttp3.OkHttpClient;
import okhttp3.Response;
import okio.ByteString;

/**
 * MyWsManager管理类
 */
public class MyWsManager {
    private  Toast toast;
    private Handler handler;

    private final String TAG = this.getClass().getSimpleName();

    private static final String URL = "ws://426k04070x.qicp.vip/websocket";     //连接地址
    @SuppressLint("StaticFieldLeak")
    private static MyWsManager wsManager;
    @SuppressLint("StaticFieldLeak")
    private static WsManager myWsManager;
    private Context context;
    private int point;
    //单例
    public static MyWsManager getInstance() {
        if (wsManager == null) {
            synchronized (MyWsManager.class) {
                if (wsManager == null) {
                    wsManager = new MyWsManager();
                }
            }
        }
        return wsManager;
    }

    public void init(Context context, Handler handler) {
        try {
            this.handler = handler;
            this.context = context;
            CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(context));
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .cookieJar(cookieJar)
                    .connectTimeout(10000L, TimeUnit.MILLISECONDS)
                    .readTimeout(10000L, TimeUnit.MILLISECONDS)
                    .pingInterval(15, TimeUnit.SECONDS)
                    .retryOnConnectionFailure(true)
                    .build();
            myWsManager = new WsManager.Builder(context)
                    .client(okHttpClient)
                    .needReconnect(true)
                    .wsUrl(URL)
                    .build();
            //.needReconnect(true)                  //是否需要重连
            //.setHeaders(null)                     //设置请求头
            //.setReconnnectInterval(10*1000)       //设置重连步长(ms)
            //.setReconnnectIMaxTime(30*1000)       //设置重连最大时长
            myWsManager.setWsStatusListener(wsStatusListener);
            myWsManager.startConnect();
        } catch (Exception e) {
            e.printStackTrace();
            Log.i(TAG, "myWsManager-----Exception");
        }
    }

    private final WsStatusListener wsStatusListener = new WsStatusListener() {
        @Override
        //此处表示连接成功后进行的操作
        public void onOpen(Response response) {
            Log.d(TAG, "myWsManager-----onOpen");
            Log.e("onOpen", "服务器连接成功");
        }

        //在这里接收和处理收到的ws数据
        @Override
        public void onMessage(String text) {
            Log.d(TAG, "MyWsManager-----onMessage");
            Log.e("onMessage", text + "\n\n");
            if (isInteger(text)){
                //这里进行分数处理的操作操作
                ParameterSet.opponentScore = Integer.parseInt(text);
            }else if ("匹配成功".equals(text)){
                //在这里进行匹配成功的跳转
                Message message = handler.obtainMessage();
                message.what = 1;
//                可以设置传回的值
                message.arg1 = 1;
                message.obj = "游戏开始";
                handler.sendMessage(message);
            }else if("匹配失败".equals(text)){
                Message message = handler.obtainMessage();
                message.what = 2;
//                可以设置传回的值
                message.arg1 = 1;
                message.obj = "匹配失败";
                handler.sendMessage(message);
            }
        }

        @Override
        public void onMessage(ByteString bytes) {
            Log.d(TAG, "MyWsManager-----onMessage");
        }

        @Override
        public void onReconnect() {
            Log.d(TAG, "MyWsManager-----onReconnect");
            Log.e("onReconnect", "服务器重连接中...");
        }

        @Override
        public void onClosing(int code, String reason) {
            Log.d(TAG, "MyWsManager-----onClosing");
            Log.e("onClosing", "服务器连接关闭中...");

            if (myWsManager != null) {
                myWsManager.stopConnect();
                myWsManager.startConnect();
            }

        }

        @Override
        public void onClosed(int code, String reason) {
            ParameterSet.INSTANCE.isOnline = false;
            Log.d(TAG, "MyWsManager-----onClosed");
            Log.e("onClosed", "服务器连接已关闭...");
        }

        @Override
        public void onFailure(Throwable t, Response response) {
            Log.d(TAG, "MyWsManager-----onFailure");
            Log.e("onFailure", "服务器连接失败...");
        }
    };

    //发送ws数据
    public void sendData(String content) {

        if (myWsManager != null && myWsManager.isWsConnected()) {
            boolean isSend = myWsManager.sendMessage(content);
            if (isSend) {
                Log.i("onOpen sendMessage", "发送成功");
            } else {
                Log.i("onOpen sendMessage", "发送失败");
            }
        } else {
            //Toast.makeText(mContext, "请先连接服务器", Toast.LENGTH_SHORT).show();
        }

    }

    //断开ws
    public void disconnect() {
        ParameterSet.INSTANCE.isOnline = false;
        if (myWsManager != null)
            myWsManager.stopConnect();
    }

//    判断字符串是不是整数
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

}